package com.demo.servlet.utils;

import com.aspose.words.*;
import com.demo.servlet.entity.Staff;
import freemarker.template.utility.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.text.html.parser.Entity;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * createby lzx 2021-01-26
 */
public class tableDate {
    public static final String DocumentBuilderAndSaveOut = "DocumentBuilderAndSaveOut.docx";
    public static final String output = "./output/";
    public static final String school_template = "school_template.docx";
    public static final long datast = System.currentTimeMillis();
    private static final Logger LOGGER = LoggerFactory.getLogger(PieChart.class);


    public static void main(String[] args) throws Exception {
        Document doc = new Document(school_template);

        //指定表格插入数据
        List<Staff> entity1 = new ArrayList<>();
        Staff staff11 = new Staff();staff11.setName("信息学院");staff11.setValue("100");staff11.setGrade("2016");  staff11.setDoubles(new double[]{500});
        Staff staff12 = new Staff();staff12.setName("计算机学院");staff12.setValue("200");staff12.setGrade("2017"); staff12.setDoubles(new double[]{600});
        Staff staff13 = new Staff();staff13.setName("会计院系");staff13.setValue("300");staff13.setGrade("2016"); staff13.setDoubles(new double[]{700});
        Staff staff14 = new Staff();staff14.setName("肌电院系");staff14.setValue("400");staff14.setGrade("2017"); staff14.setDoubles(new double[]{800});
        entity1.add(staff11);entity1.add(staff12);  entity1.add(staff13); entity1.add(staff14);
        for (int i = 0; i< entity1.size(); i++){
            entity1.get(i).setIndex(i+1);
        }
        /************************************************************************/
//        addexcel(doc,0,entity1);
//        tableTotitle(doc,"1.",0);

        Map<String, List<Staff>> map = new HashMap<>();
        map = entity1.stream().collect(Collectors.groupingBy(Staff::getGrade,Collectors.toList()));
        map.forEach((k, v) ->{
            if ("2016".equals(k)){
                try {
                    addexcel(doc,0,v);
                    tableTotitle(doc,"1.",0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if ("2017".equals(k)){
                try {
                    addexcel(doc,0,v);
                    tableTotitle(doc,"2.",0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
                }
        );

        //第一步 获取表格模板
        //第二步 根据size复制表格模板
        //第三步


        /********************************************************************************/
        doc.save(output + datast + DocumentBuilderAndSaveOut);
    }


    /*向已有表格模板中插入数据*/
    public static  void addexcel(Document doc,int index,List<Staff> staff)throws  Exception{
        Table table = (Table) doc.getChild(NodeType.TABLE, index, true);
        for (Staff staf : staff) { // 替换变量
            Node deepClone = table.getLastRow().deepClone(true); //得到最后一行
            Range range = table.getLastRow().getRange();//得到值
            range.replace("index",String.valueOf(staf.getIndex()), true, true);
            range.replace("name", staf.getName(), true, true);
            range.replace("value",staf.getValue(), true, true);
            table.getRows().add(deepClone);
        }
        table.getLastRow().remove();
    }





    /*将表格定位到 指定标题下*/
    public static  void tableTotitle(Document doc, String startWith, int index) throws Exception {
        NodeCollection tables = doc.getChildNodes(NodeType.TABLE, true);//找到表
        if (null==tables) {
            return;
        }
        Node tableIndex = tables.get(index);
        //查找标题
        NodeCollection paras = doc.getChildNodes(NodeType.PARAGRAPH, true);
        if (null == paras) {
            return;
        }
        Paragraph insertPoint = null;
        for (Node node : paras.toArray()) {
            Paragraph p = (Paragraph)node;
            if (null!=p && p.getText().startsWith(startWith)) {
                insertPoint = p;
                break;
            }
        }
        if (null == insertPoint) {
            return;
        }
        insertPoint.getParentNode().insertAfter(tableIndex,insertPoint);
    }

    private  static  void  save(Document doc,long old)throws Exception{
        String docxName = datast+DocumentBuilderAndSaveOut;
        doc.save(output+docxName);
        long now = System.currentTimeMillis();
        System.out.println("共耗时：" + ((now - old) / 1000.0) + "秒"); // 转化用时
        doc.save(output + datast + DocumentBuilderAndSaveOut);
    }

}